package com.tydic.daily.user;

import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.tydic.daily.exception.CustomException;
import com.tydic.daily.user.po.DailyUser;
import com.tydic.daily.user.service.UserLoginService;
import com.tydic.daily.user.vo.ActiveUser;
import com.tydic.daily.utils.StringUtil;

@Controller
@RequestMapping("userLogin")
public class UserLoginController {
	private static Logger log = Logger.getLogger(UserLoginController.class);
	@Autowired
	UserLoginService userLoginService;
	
	@RequestMapping("registUser")
	public String registUser(HttpServletRequest request) {

		String username = request.getParameter("registusername");
		String userpwd = request.getParameter("userpwd");
		String name = request.getParameter("name");
		String useremail = request.getParameter("useremail");
		String usercompany = request.getParameter("usercompany");
		String userdepartment = request.getParameter("userdepartment");
		String userworkid = request.getParameter("userworkid");

		if (StringUtil.isNullString(username)
				|| StringUtil.isNullString(userpwd)
				|| StringUtil.isNullString(name)
				|| StringUtil.isNullString(useremail)
				|| StringUtil.isNullString(usercompany)) {
			return "login/registFailure";
		}
		DailyUser dailyUser = new DailyUser();
		String salt = getUUID();
		String pwd = getMD5(salt, userpwd);
		dailyUser.setUsername(username);
		dailyUser.setSaltvalue(salt);
		dailyUser.setUserpwd(pwd);
		dailyUser.setIstydic(true);
		dailyUser.setName(name);
		dailyUser.setUsercompany(usercompany);
		dailyUser.setUseremail(useremail);
		if (!userdepartment.equals("请选择...")) {
			dailyUser.setUserdepartment(userdepartment);
		}
		if (!StringUtil.isNullString(userworkid)) {
			dailyUser.setUserworkid(userworkid);
		}
		int registUser = userLoginService.registUser(dailyUser);
		if (registUser == 1) {
			return "login/registSuccess";
		} else {
			return "login/registFailure";
		}
	}

	@RequestMapping("index")
	public String index(Model model) throws Exception {
		// 从shiro的session中取activeUser
		Subject subject = SecurityUtils.getSubject();
		// 取身份信息
		ActiveUser activeUser = (ActiveUser) subject.getPrincipal();
		// 通过model传到页面
		model.addAttribute("activeUser", activeUser);
		return "userview/index";
	}

	@RequestMapping("getValidForRegistUsername")
	@ResponseBody
	public String getValidForRegistUsername(HttpServletRequest request,
			HttpServletResponse response) {
		String userName = request.getParameter("registusername");
		int validForRegistUsername = userLoginService
				.getValidForRegistUsername(userName);
		String valueOf = String.valueOf(validForRegistUsername);
		return valueOf;
	}

	@RequestMapping("loginuser")
	public String loginuser(HttpServletRequest request) throws Exception {
		// 如果登陆失败从request中获取认证异常信息，shiroLoginFailure就是shiro异常类的全限定名
		String exceptionClassName = (String) request.getAttribute("shiroLoginFailure");
		// 根据shiro返回的异常类路径判断，抛出指定异常信息
		if (exceptionClassName != null) {
			if (UnknownAccountException.class.getName().equals(
					exceptionClassName)) {
				return "login/registFailure";
			} else if (IncorrectCredentialsException.class.getName().equals(
					exceptionClassName)) {
				return "login/registFailure";
			} else {
				throw new Exception();// 最终在异常处理器生成未知错误
			}
		}
		// 此方法不处理登陆成功（认证成功），shiro认证成功会自动跳转到上一个请求路径
		// 登陆失败还到login页面
		return "login/login";
	}

	public static String getUUID() {
		String s = UUID.randomUUID().toString();
		// 去掉“-”符号
		return s.substring(0, 8) + s.substring(9, 13) + s.substring(14, 18)
				+ s.substring(19, 23) + s.substring(24);
	}

	public static String getMD5(String salt, String pwd) {
		String md5 = new Md5Hash(pwd, salt).toString();// 还可以转换为
														// toBase64()/toHex()
		return md5;
	}
}
